<template>
<div class="add-cat">
    <a-form :model="formData" ref="formref" :labCol="{display:'none'}" :rules="rules" @finish="addNewCAt">
        <a-form-item name="catname"   hasFeedback>
            <a-input v-model:value="formData.catname" placeholder="栏目名称" />
        </a-form-item>        
        <a-form-item name="parentid"  hasFeedback>
            <a-select v-model:value="formData.parentid" >
                <a-select-option v-for="(item,key) in catList" :value="item.catid" :key="catList[key].catid">{{item.catname}}</a-select-option>
            </a-select>
        </a-form-item>
        <a-form-item name="type">
            <a-select v-model:value="formData.type" :options="catTypes">
            </a-select>
        </a-form-item>
        <a-form-item name="description"  >
            <a-input v-model:value="formData.description" placeholder="栏目描述" />
        </a-form-item>
        <a-form-item>
            <div id="content"  ></div>
        </a-form-item>
        <a-form-item class="text-center">
            <a-button type="primary" html-type="submit"  >确认添加</a-button>
        </a-form-item>
    </a-form>
</div>
</template>
<style lang="less" scoped>
.add-cat{
    padding:10px 10px;
}

#content{
    :deep(.w-e-text){
        height: 550px;
    }

}
</style>
<script>
import { message } from 'ant-design-vue';
import { defineComponent, onMounted, reactive,ref, toRaw,watch} from 'vue';
import {catTopList,catInsert} from '@/api/content';
import E from 'wangeditor-antd';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';

export default defineComponent({
    emits:['resetData'],
    setup(props,context) {
        const store=useStore();
        message.config({top:'200px',duration:1.2});
        let editor = ref();
        let imgsrc=[];
        let parentid=0;
        const route=useRoute();
        if(route.params)
        {
            parentid=route.params['catid'];            
        }

        watch(
            ()=>route.params['catid'],
            ()=>{
                parentid=route.params['catid'];
            }
        );

        const formData=reactive({
            catname:'',
            parentid:parentid,
            description:'',
            content:'',
            type:1
        });

        const catTypes=[
            {label:'栏目',value:1},
            {label:'单页',value:2}
        ];

        
        

        const formref=ref();

        const catList=reactive([]);

        catTopList().then(
            res=>{               
                                
                if(res.data['code']==200)
                {
                    
                    Object.assign(catList,[{catid:0,catname:'顶级栏目'},...res.data['data']]);
                    formData.parentid=Number(parentid);
                    
                    
                }
                
            },
            err=>{
                console.log(err);
            }
        );

        

        const checkCatname= async (_rules,value) =>{
            if(!value){
                return Promise.reject('不能为空');
            }
            return Promise.resolve();
        };

        const rules={
            catname:[{required:true,validator:checkCatname,trigger:'change'}],
        };

        const addNewCAt = () =>{
            let obj={...toRaw(formData),imgs:imgsrc};        
            
            catInsert(obj).then(
                res=>{
                    
                    if(res.data['code']==200){
                        message.success('添加栏目成功');
                        context.emit('resetData');
                    }
                    else{
                        message.error(res.data['msg']);
                    }
                },
                err=>{
                    console.log(err);
                }
            )

        };

        

        onMounted(()=>{
            
            editor.value = new E('#content');
            editor.value.customConfig.menus = [
                'head',  // 标题
                'bold',  // 粗体
                'fontSize',  // 字号
                'fontName',  // 字体
                'italic',  // 斜体
                'foreColor',  // 文字颜色
                'backColor',  // 背景颜色
                'link',  // 插入链接
                'list',  // 列表
                'justify',  // 对齐方式
                'quote',  // 引用
                'emoticon',  // 表情
                'image',  // 插入图片
                'table',  // 表格
                'code',  // 插入代码
                'undo',  // 撤销
                ];
            editor.value.customConfig.uploadImgServer=import.meta.env.VITE_BASE_URL+"/Files/img";            
            editor.value.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
            editor.value.customConfig.uploadFileName = 'image';
            editor.value.customConfig.uploadImgTimeout = 15000;
            editor.value.customConfig.uploadImgHeaders = {'access-token':store.getters['auth/tokken']};
            editor.value.customConfig.onchange=function (newHtml) {                
                formData.content=newHtml;
            };
            editor.value.customConfig.uploadImgHooks = {
                customInsert: function (insertImg, result, editor) {
                    
                    if(result['code']==200)
                    {
                        let url=result['data'];
                        insertImg(url);
                        imgsrc.push(url);
                    }
                    else if(result['code']==0)
                    {
                        message.error(result['msg']);
                    }
                },
                timeout: function (xhr, editor) {
                    //console.log(xhr);                    
                    message.error('上传超时');
                },
                error: function (xhr, editor) {
                   // console.log(xhr);
                    
                }
            };
            editor.value.create();
            
        });


        return{
            formData,formref,rules,addNewCAt,catList,catTypes
        }


    },
})
</script>
